﻿using LiSAClient.Core;
using LiSAClient.Core.Interfaces;
using LiSAClient.Core.Messages;
using LiSAClient.LiSAService;
using log4net.Config;

namespace LiSAClient.WpfClient.Utils
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    using GalaSoft.MvvmLight.Messaging;

    public class AppHandler : IAppContext
    {
        protected readonly WindowHandler WindowHandler;

        protected readonly ErrorHandler ErrorHandler;
        
        public AppHandler()
        {
            AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(AssemblyLoader.AssemblyInitializer);
            XmlConfigurator.Configure(new FileInfo("log4net.config"));

            Messenger.Default.Register<LoginCompletedMessage>(this, this.LoggedIn);
            this.WindowHandler = new WindowHandler();
            this.ErrorHandler = new ErrorHandler();
            this.Permissions = new HashSet<string>();

            AppContext.CurrentContext = this;

            Messenger.Default.Register<LogoutMessage>(this, this.Handle);
            Messenger.Default.Send(new ShowMainWindowMessage());
        }

        private void Handle(LogoutMessage obj)
        {
            Messenger.Default.Send(new ShowMainWindowMessage());
        }

        private void LoggedIn(LoginCompletedMessage obj)
        {
            this.User = obj.LoggedInUser;
            if (this.User != null && this.User.Permissions != null && this.User.Permissions.Any())
            {
                this.Permissions = new HashSet<string>(this.User.Permissions.Select(x => x.Role.ToString()));
            }
        }

        #region IAppContext
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        private User user;

        public User User
        {
            get
            {
                return this.user;
            }

            private set
            {
                this.user = value;
                this.OnPropertyChanged("User");
            }
        }

        public ISet<string> Permissions { get; private set; }

        #endregion
    }
}
